package com.wanggsx.library.util;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.location.LocationManager;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.provider.Settings;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.wanggsx.library.base.app.needextends.SuperAppInstance;

import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.List;
import java.util.Locale;

/**
 * desc  : 定位相关工具类
 */
public class UtilsLocation {

    /**
     * 判断Gps是否可用
     *
     * @return {@code true}: 是<br>{@code false}: 否
     */
    public static boolean isGpsEnabled() {
        LocationManager lm = (LocationManager) SuperAppInstance.appInstance.getSystemService(Context.LOCATION_SERVICE);
        return lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
    }

    /**
     * 判断定位是否可用
     *
     * @return {@code true}: 是<br>{@code false}: 否
     */
    public static boolean isLocationEnabled() {
        LocationManager lm = (LocationManager) SuperAppInstance.appInstance.getSystemService(Context.LOCATION_SERVICE);
        return lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)
                || lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
    }

    /**
     * 打开Gps设置界面
     */
    public static void openGpsSettings() {
        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        SuperAppInstance.appInstance.startActivity(intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
    }

    private UtilsLocation() {
    }

    private static AMapLocationClient mLocationClient;
    private static AMapLocationClientOption mLocationOption;
    private static AMapLocation mLocationResult;
    private static String mAddr;
    private static WeakReference<Context> mActivity;
    private static LocationAddressListener mListener;

    public interface LocationAddressListener {
        void onGetAddress(AMapLocation location, String addr);
    }

    /**
     * 获取经纬度
     */
    public static void getJingWeiDuAndAddress(Activity activity, LocationAddressListener listener) {
        if (activity == null || listener == null) return;
        if (mLocationResult != null && mLocationResult.getLatitude() > 0 && mLocationResult.getLongitude() > 0) {
            listener.onGetAddress(mLocationResult, getAddress(activity, mLocationResult.getLatitude(), mLocationResult.getLongitude()));
            return;
        }
        //保存Context
        mActivity = new WeakReference<>(activity.getApplicationContext());
        mListener = listener;
        if (mLocationClient == null) {
            //初次开启定位
            mLocationClient = new AMapLocationClient(activity.getApplicationContext());
            //设置定位回调监听，这里要实现AMapLocationListener接口，AMapLocationListener接口只有onLocationChanged方法可以实现，用于接收异步返回的定位结果，参数是AMapLocation类型。
            mLocationClient.setLocationListener(new AMapLocationListener() {
                @Override
                public void onLocationChanged(final AMapLocation aMapLocation) {
                    mLocationResult = aMapLocation;
                    mLocationClient.stopLocation();
                    if (mLocationResult != null) {
                        //继续获取地址
                        mAddr = getAddress(mActivity.get(), mLocationResult.getLatitude(), mLocationResult.getLongitude());
                        //回调
                        mListener.onGetAddress(mLocationResult, mAddr);
                    }
                }
            });
        }
        //初始化定位参数
        mLocationOption = new AMapLocationClientOption();
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置是否只定位一次,默认为false
        mLocationOption.setOnceLocation(true);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        mLocationClient.startLocation();
    }

    /**
     * 获取地址
     */
    public static String getAddress(Context context, double latitude, double longitude) {
        Geocoder geocoder = new Geocoder(context, Locale.getDefault());
        try {
            List<Address> addresses = geocoder.getFromLocation(latitude,
                    longitude, 1);
            if (addresses.size() > 0) {
                Address address = addresses.get(0);
                StringBuilder sb = new StringBuilder();
                sb.append(address.getAddressLine(0));
                return sb.toString();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
        }
    };
}
